<template>
    <el-dialog :model-value="props.value" title="设置资产属性" width="800px" @closed="props.closed">
        <el-form ref="formRef" :model="form" label-width="120px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="属性名称" prop="displayName">
                        <el-input v-model="form.displayName" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="标识符" prop="attributeName">
                        <el-input v-model="form.attributeName" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <AttributeFormItem
                        label="属性值"
                        :attribute="props.rowData as any"
                        prop="value"
                        :form-data="form"
                        v-model="form.value"
                    />
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="props.close">取消</el-button>
                <el-button type="primary" @click="onSubmit" :loading="loading">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { type PopupBoxProps, tryJsonParse } from '@great/utils';
import { IoTDeviceService } from '@great/services';
import { useRequest } from 'vue-request';
import type { FormInstance } from 'element-plus';
import { AttributeFormItem } from '@great/components';

interface IProps extends PopupBoxProps {
    rowData: Record<string, any>;
    callback?: () => void;
}

const props = defineProps<IProps>();

const formRef = useTemplateRef<FormInstance>('formRef');
const form = reactive({
    displayName: '',
    attributeName: '',
    value: '',
    ...props.rowData
});

function onSubmit() {
    formRef.value?.validate(async (valid: boolean) => {
        if (valid) {
            run();
        }
    });
}

const { run, loading } = useRequest(
    () => {
        const dtoList = [{ attributeName: form.attributeName, value: form.value }];
        const { relation } = tryJsonParse(props.rowData.additionalDefinition, {});
        if (relation.length > 1) {
            dtoList.push({
                attributeName: `${form.attributeName}Object`,
                value: form[`${props.rowData.objectName}.${form.attributeName}Object`]
            });
        }
        return IoTDeviceService.updateAttributeValue({
            objectName: props.rowData.objectName,
            dataId: props.rowData.dataId,
            dtoList
        });
    },
    {
        manual: true,
        onSuccess() {
            props.close();
            props.callback?.();
        }
    }
);
</script>

<style lang="scss" scoped></style>
